use chrono::Local;
/**
 * 恢复区数据库操作
 */
use diesel::prelude::*;
use crate::model::recovery_list_model::*;
use crate::schema::recovery_lists::dsl::*;

/// Run query using Diesel to find user by uid and return it.
pub fn find_by_id(
    recovery_list_id: &str,
    conn: &SqliteConnection,
) -> Result<Option<RecoveryList>, super::DbError> {

    let recovery_list = recovery_lists
        .filter(id.eq(recovery_list_id))
        .first::<RecoveryList>(conn)
        .optional()?;

    Ok(recovery_list)
}

pub fn find_by_page(
    page: i64,
    size: i64,
    conn: &SqliteConnection,
) -> Result<(Option<Vec<RecoveryList>>, i64), super::DbError> {

    let offset = (page - 1) * size;

    let recovery_list_vec = recovery_lists
        .order(create_time.desc())
        .limit(size)
        .offset(offset)
        .load::<RecoveryList>(conn)
        .optional()?;

    let count = recovery_lists.count().get_result::<i64>(conn)?;

    Ok((recovery_list_vec, count))
    
}


pub fn find_expired(
    page: i64,
    size: i64,
    conn: &SqliteConnection,
) -> Result<(Option<Vec<RecoveryList>>, i64), super::DbError> {

    let offset = (page - 1) * size;

    let now = Local::now().timestamp_millis();

    let recovery_list_vec = recovery_lists
        .filter(expire_time.le(now))
        .order(create_time.desc())
        .limit(size)
        .offset(offset)
        .load::<RecoveryList>(conn)
        .optional()?;

    let count = recovery_lists.count().get_result::<i64>(conn)?;

    Ok((recovery_list_vec, count))
    
}

/// Run query using Diesel to insert a new database row and return the result.
pub fn insert(
    // prevent collision with `name` column imported inside the function
    new_recovery_list: RecoveryList,
    conn: &SqliteConnection,
) -> Result<RecoveryList, super::DbError> {

    diesel::insert_into(recovery_lists).values(&new_recovery_list).execute(conn)?;

    Ok(new_recovery_list)
}




pub fn delete_by_id(
    record_id: &str,
    conn: &SqliteConnection,
) -> Result<(), super::DbError> {
    
    diesel::delete(recovery_lists).filter(id.eq(record_id)).execute(conn)?;
    Ok(())
}